package com.huafv.reggie.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.huafv.reggie.common.R;
import com.huafv.reggie.dto.DishDto;
import com.huafv.reggie.entity.Category;
import com.huafv.reggie.entity.Dish;
import com.huafv.reggie.service.CategoryService;
import com.huafv.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 菜品管理
 */
@Slf4j
@RestController
@RequestMapping("/dish")
public class DishController {

    @Resource
    private DishService dishService;

    @Resource
    private CategoryService categoryService;

    /**
     * 新增菜品
     * @param dto Dto
     */
    @PostMapping
    public R<String> save(@RequestBody DishDto dto){
        dishService.saveWithFlavor(dto);
        return R.success("新增菜品成功");
    }

    /**
     * 菜品信息分页查询
     *
     * @param page     当前页
     * @param pageSize 页大小
     * @param name     关键词
     */
    @GetMapping("/page")
    public R<Page<DishDto>> list(int page, int pageSize, String name){
        // 构建分页构造器对象
        Page<Dish> dishPage = new Page<>(page, pageSize);
        Page<DishDto> dishDtoPage = new Page<>();
        // 条件构造器
        LambdaQueryWrapper<Dish> dishLambdaQueryWrapper = new LambdaQueryWrapper<>();
        dishLambdaQueryWrapper.like(StringUtils.isNotEmpty(name), Dish::getName, name);
        dishLambdaQueryWrapper.orderByDesc(Dish::getUpdateTime);
        // 查询
        dishService.page(dishPage, dishLambdaQueryWrapper);

        // 对象拷贝
        BeanUtils.copyProperties(dishPage, dishDtoPage, "records");

        List<Dish> records = dishPage.getRecords();


        List<DishDto> dishDtoList = records.stream().map((e) -> {
            DishDto dto = new DishDto();
            BeanUtils.copyProperties(e, dto);

            Long categoryId = e.getCategoryId();
            Category category = categoryService.getById(categoryId);
            String categoryName = category.getName();
            dto.setCategoryName(categoryName);

            return dto;
        }).collect(Collectors.toList());


        dishDtoPage.setRecords(dishDtoList);

        return R.success(dishDtoPage);
    }

    /**
     * 通过Id获取单个菜品信息
     * @param id 菜品Id
     */
    @GetMapping("{id}")
    public R<DishDto> get(@PathVariable Long id){
        return R.success(dishService.getByIdWithFlavor(id));
    }


    /**
     * 新增菜品
     * @param dto Dto
     */
    @PutMapping
    public R<String> update(@RequestBody DishDto dto){
        dishService.updateWithFlavor(dto);
        return R.success("更新菜品信息成功");
    }
}